package com.autorun.server.controller;

import com.autorun.server.dto.ApiResponse;
import com.autorun.server.dto.LoginRequest;
import com.autorun.server.dto.LoginResponse;
import com.autorun.server.entity.User;
import com.autorun.server.service.UserService;
import com.autorun.server.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 认证控制器
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     * 
     * @param request 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            log.info("收到登录请求 - 用户名: {}", request.getUsername());

            // 验证用户
            User user = userService.login(request);

            // 生成JWT token
            String token = jwtUtil.generateToken(user.getId(), user.getUsername());

            // 构造响应
            LoginResponse response = new LoginResponse(token, user);

            log.info("登录成功 - 用户: {}, ID: {}", user.getUsername(), user.getId());
            return ApiResponse.success("登录成功", response);

        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage(), e);
            return ApiResponse.error("登录失败: " + e.getMessage());
        }
    }
}